// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let msgtype = event.MsgType
  let Content = event.Content
  let sendmsg = ''
  let data = {
    "reqType": 0,
    "perception": {
      "inputText": {
        "text": Content
      }
    },
    "userInfo": {
      "apiKey": "f75c4eefe1c744cfa3bb1cd647f4c7db",
      "userId": "526084"
    }
  }
  
  switch (msgtype) {
    case 'text':
      try {
        let response = await axios.post('http://openapi.tuling123.com/openapi/api/v2', data)
        let resdata = response.data.results[0].values.text
        sendmsg = resdata ? resdata : '收到啦'
      } catch (err) {
        sendmsg = '接口出错了'
        console.log('接口出错了', error)
      }
      break;
    case 'event':
      sendmsg = '您好，我是笨笨的机器人，你可以和我聊天哦'
      //   await cloud.openapi.customerServiceMessage.send({
      //   touser: wxContext.OPENID,
      //   msgtype: 'text',
      //   text: {
      //     content: sendmsg,
      //   },
      // })
      break;
    case 'miniprogrampage':
      sendmsg = '卡片不错哦！'
      break;
    case 'image':
      sendmsg = '图片非常漂亮'
      break;
    default:
      sendmsg = '不错哦！'
      break;
  }

  await cloud.openapi.customerServiceMessage.send({
    touser: wxContext.OPENID,
    msgtype: 'text',
    text: {
      content: sendmsg,
    },
  })
  // if (process.env.author == wxContext.OPENID){
  //   return '作者'
  // }
  // const formatTime = time => {
  //   var date = new Date(time);
  //   var year = date.getFullYear()
  //   var month = date.getMonth() + 1
  //   var day = date.getDate()
  //   return [year, month, day].map(formatNumber).join('-')
  // }
  // const formatNumber = n => {
  //   n = n.toString()
  //   return n[1] ? n : '0' + n
  // }

  // console.log(formatTime((new Date).getTime()))
  // try {
  //   await cloud.openapi.subscribeMessage.send({
  //     touser: process.env.author,
  //     page: 'pages/mine/mine',
  //     templateId: '86OHf1b4SUipis3L89BfMIZoW4I0wWTDFThW6x5zaYA',
  //     data: {
  //       name1: {
  //         value: '客服消息'
  //       },
  //       thing2: {
  //         value: Content
  //       },
  //       time3: {
  //         value: formatTime((new Date).getTime())
  //       }
  //     }
  //   })
  // }catch (err){
  //  console.log(err)
  // }




}


